<?php
/**
 * Created by PhpStorm.
 * User: liyiming
 * Date: 2021/1/6
 * Time: 13:26
 */
header("Content-type:text/html;charset=utf-8");
class serviceController extends commonController
{

    /**
     * 向微信服务器 使用登录凭证 code 获取 session_key 和 openid , unionID  , 或手机号
     */
    public function decodeUserInfoAction()
    {
        $config = Config::getInstance();
        $wechat = $config->getWechat();
        $GetInfo = file_get_contents("php://input");

        $log = new Logging();
        $log->lfile("decodeUserInfo");
        $log->lwrite('receive：' . $GetInfo);

        $info = json_decode($GetInfo, true);
        $CheckCode = strtoupper(substr(md5('shjieta'), 0, 16));

        if (!isset($info['check_code']) || !isset($info['version']) || !isset($info['code']) || !isset($info['encryptedData']) || !isset($info['iv'])
            || empty($info['check_code']) || empty($info['version']) || empty($info['code']) || empty($info['encryptedData']) || empty($info['iv'])
        ) {
            $result = json_encode(['errcode' => 1, 'errormsg' => '参数错误'], JSON_UNESCAPED_UNICODE);
            $log->lwrite('error' . $result);
            echo $result;
            exit;
        }

        if ($CheckCode !== $info['check_code']) {
            $result = json_encode(['errcode' => 1, 'errormsg' => '校验码错误'], JSON_UNESCAPED_UNICODE);
            $log->lwrite('error' . $result);
            echo $result;
            exit;
        }
        if ($info['version'] == 10) {

            $url = 'https://api.weixin.qq.com/sns/jscode2session';
            $param = array();
            $param['appid'] = $wechat['riders_appid'];
            $param['secret'] = $wechat['riders_appsecret'];
            $param['js_code'] = $info['code'];
            $param['grant_type'] = 'authorization_code';


            $oCurl = curl_init();
            if (stripos($url, "https://") !== FALSE) {
                curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
                curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
                curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
            }
            curl_setopt($oCurl, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8'));
            $aPOST = array();
            foreach ($param as $key => $val) {
                $aPOST[] = $key . "=" . urlencode($val);
            }
            $strPOST = join("&", $aPOST);

            curl_setopt($oCurl, CURLOPT_URL, $url);
            curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($oCurl, CURLOPT_POST, true);
            curl_setopt($oCurl, CURLOPT_POSTFIELDS, $strPOST);
            curl_setopt($oCurl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);

            $sContent = curl_exec($oCurl);
            $aStatus = curl_getinfo($oCurl);
            curl_close($oCurl);

            if (intval($aStatus["http_code"]) == 200) {
                $log->lwrite('  sContent：' . $sContent);
                $user_info = json_decode($sContent, true);
                if (isset($user_info['session_key'])) {
                    $pc = new WXBizDataCrypt($param['appid'], $user_info['session_key']);
                    $errCode = $pc->decryptData($info['encryptedData'], $info['iv'], $data);
                    $log->lwrite('errCode：' . $errCode . ', data:' . $data);

                    $data = json_decode($data, true);
                    if ($errCode == 0) {
                        //存会员资料，且回传会员资料
                        $member_data = $this->saveUserData($data, $info['phone']);
                        $log->lwrite('member_data:' . json_encode($member_data, JSON_UNESCAPED_UNICODE));
                        $data = array_merge($data, $member_data);
                    }

                    $result = json_encode(['errcode' => 0, 'errormsg' => '', 'data' => $data], JSON_UNESCAPED_UNICODE);
                    $log->lwrite('response：' . $result);
                    echo $result;
                    exit;
                } else {
                    $result = json_encode(['errcode' => 1, 'errormsg' => '查询有误'], JSON_UNESCAPED_UNICODE);
                    $InfoDatasT = json_encode($param, JSON_UNESCAPED_UNICODE);
                    $log->lwrite('error' . $result . '  param：' . $InfoDatasT);
                    $log->lwrite("curl result:" . $sContent);
                    echo $result;
                    exit;
                }
            } else {
                $result = json_encode(['errcode' => 1, 'errormsg' => '网络连线有误'], JSON_UNESCAPED_UNICODE);
                $log->lwrite('error' . $result);
                echo $result;
                exit;
            }

        } else {
            $result = json_encode(['errcode' => 1, 'errormsg' => '未知版本'], JSON_UNESCAPED_UNICODE);
            $log->lwrite('error' . $result);
            echo $result;
            exit;
        }

    }

    /**
     *  若OPENID 不存在， 新增会员， 若OPENID存在，则更新微信信息
     */
    private function saveUserData($data, $phone)
    {

        if (isset($data['openId'])) {
            $where = array("AND" => array("=" => array('openId' => $data['openId'], 'isdeleted' => 0)));
            $result = $this->model->getItemByOther($where, 'riders');
            $field = array();
            $field['unionId'] = isset($data['unionId']) ? $data['unionId'] : '';
            $field['wx_info'] = json_encode($data, JSON_UNESCAPED_UNICODE);
            $field['username'] = Tools::userTextEncode($data['nickName']);;
            $field['last_login_time'] = date('Y-m-d H:i:s');
            $member_id = 0;
            $mobile = $phone;
            if (!empty($result) && count($result) > 0) {
                $member_id = $result[0]['id'];
                $mobile = empty($result[0]['tel']) ? $mobile : $result[0]['tel'];
                if (empty($result[0]['tel']) && !empty($mobile)) {
                    $field['tel'] = $mobile;
                    $field['regist_date'] = date('Y-m-d H:i:s');
                }
                $where_fields = array("AND" => array("=" => array('id' => $member_id, 'isdeleted' => 0)));
                $r = $this->model->updateItem($field, $where_fields, 'riders');
            } else {
                if (!empty($mobile)) {
                    $field['tel'] = $mobile;
                    $field['regist_date'] = date('Y-m-d H:i:s');
                }
                $field["openId"] = $data['openId'];
                $field['status'] = 10;
                $field['isdeleted'] = 0;
                $field['createdt'] = 'now()';
                $member_id = $this->model->addItem($field, 'riders');
            }


            return array("mID" => $member_id, "mobile" => $mobile, "check" => $result[0]['status']);
        }

        return array();
    }


    public function riders_approveAction(){
        $table = 'riders';
        $Data = $this->params;
        $file = 'riders_approve';
        self::WriteReception($file,json_encode($Data,JSON_UNESCAPED_UNICODE));

//        var_dump($_FILES);
//        var_dump($Data);
//        var_dump(urldecode($Data['name']));
//        die;
//        if (!is_uploaded_file($_FILES['file']['tmp_name'])) {

//            $getOrderData = file_get_contents("php://input");
//            $Data = json_decode($getOrderData, true);
//        }
//        ,'recitePaths'=>'string','health'=>'string'
        $where_fields = array("AND" => array("=" => array("tel" => $Data["mobile"])));
        $validate = ['check_code'=>'check','store'=>'string','mobile'=>'phone',];
        if($Data['t'] == 1){
            $validate = ['check_code'=>'check','name'=>'string','sex'=>'string','store'=>'string','region_0'=>'string','region_1'=>'string','region_2'=>'string','region2_0'=>'string','region2_1'=>'string','region2_2'=>'string','detailed_address'=>'string','date'=>'string',
                'mobile'=>'phone','id_card'=>'id_card','resume'=>'string','emergency_contact'=>'string','emergency_contact_mobile'=>'phone','relation'=>'string'];
            self::Verify($Data,$validate,$file,Data::$VERSION);

            if (isset($_FILES['file']) && $_FILES['file']['name'] !== '') {
                $dir = $this->model->Uploaddir("riders/".$Data['store']);
                $upload_result = FileUpload::uploadSingle('file', 'riders_'.time().'f', '', $dir);
                if ($upload_result != "") {
                    if ($upload_result == "filesize" || $upload_result == "fileext" || $upload_result == "fileupload") {
                        $msg['msg'] = '档案过大或格式不符';
                        echo json_encode($msg);
                        exit;
                    } else {
                        $field['card_front_img'] = $Data['store'].'/'.$upload_result;
                    }
                }
            }

            $field['sex'] = $Data["sex"];
            $field['birth_date'] = $Data["date"];
            $field['province'] = $Data['region2_0'];
            $field['city'] = $Data['region2_1'];
            $field['area'] = $Data['region2_2'];
            $field['service_province'] = $Data['region_0'];
            $field['service_city'] = $Data['region_1'];
            $field['service_area'] = $Data['region_2'];
            $field['service_shop_no'] = $Data["store"];
//        $field['jkz_end'] = $Data["jkz_end"];
//        $field['jkz_start'] = $Data["jkz_start"];
            $field['name'] = $Data["name"];
//        $field['username'] = $Data["username"];
//        $field['age'] = $Data["age"];
//        $field['tel'] = $Data["tel"];
            $field['address'] = $Data["address"];
            $field['urgency_cont_username_tel'] = $Data["emergency_contact_mobile"];
            $field['urgency_relation'] = $Data["relation"];
            $field['urgency_cont_username'] = $Data["emergency_contact"];
            $field['resume'] = $Data["resume"];
            $field['id_card'] = $Data["id_card"];
            $field['initiate'] = 1;
            $r = $this->model->updateItem($field, $where_fields, $table);
            if($r){
                self::WriteResponse($file,1,'提交成功','');

            }else{
                self::WriteResponse($file,0,'请稍后重试','');

            }
        }else{
            $field['status'] = 0;
            self::Verify($Data,$validate,$file,Data::$VERSION);
            if (isset($_FILES['recitePaths']) && $_FILES['recitePaths']['name'] !== '') {
                $dir = $this->model->Uploaddir("riders/".$Data['store']);
                $upload_result = FileUpload::uploadSingle('recitePaths', 'riders_'.time().'b', '', $dir);
                if ($upload_result != "") {
                    if ($upload_result == "filesize" || $upload_result == "fileext" || $upload_result == "fileupload") {
                        self::WriteResponse($file,0,'档案过大或格式不符','');

                    } else {
                        $field['card_back_img'] = $Data['store'].'/'.$upload_result;
                    }
                }
            }

            if (isset($_FILES['health']) && $_FILES['health']['name'] !== '') {
                $dir = $this->model->Uploaddir("riders/".$Data['store']);
                $upload_result = FileUpload::uploadSingle('health', 'riders_'.time().'h', '', $dir);
                if ($upload_result != "") {
                    if ($upload_result == "filesize" || $upload_result == "fileext" || $upload_result == "fileupload") {
                        self::WriteResponse($file,0,'档案过大或格式不符','');
                    } else {
                        $field['health_cards'] = $Data['store'].'/'.$upload_result;
                    }
                }
            }

            $r = $this->model->updateItem($field, $where_fields, $table);
            if($r){
                self::WriteResponse($file,1,'','');
            }
            self::WriteResponse($file,0,'','');
        }


    }

    private function orderInfo($type,$tel,$page,$number_page){
        $_r = ['errcode' => 1, 'errormsg' => '','data'=>''];
        $whereR = array("AND" => array("=" => array('tel'=>$tel, "status"=>1, "isdeleted"=>0)));
        $ridersInfo = $this->model->getItemByOther($whereR,'riders');
        $where = '';
        if($ridersInfo && count($ridersInfo) > 0){
            $service_shop_no = $ridersInfo[0]['service_shop_no'];
            if (empty($service_shop_no)){
                return json_encode(['errcode'=> 0,'errormsg'=>'服务门店不存在'],JSON_UNESCAPED_UNICODE);exit;
            }
            $where .= " a.shop_no = $service_shop_no AND";
        }else{
            return json_encode(['errcode'=> 0,'errormsg'=>'骑手资料有误'],JSON_UNESCAPED_UNICODE);exit;
        }

        if (is_null($page)) {
            $page = 1;
        }
        if (is_null($number_page)) {
            $number_page = 10;
        }
        $offset = ($page - 1) * $number_page;
        $limit = "limit $offset, $number_page";


        if($type == 3){
            $where.= "(a.status = 3) and a.express_mobile = '$tel'";
        }elseif ($type == 5){
            $where.= "(a.status >= 5) and a.express_mobile = '$tel'";
        }elseif ($type == 4){
            $where.= "(a.status = 4) and a.express_mobile = '$tel'";
        }elseif ($type == 2){
            $where.= "(a.status = 2)";
        }
        $where .="  and a.express_type = 'self' and a.isdeleted = 0";
        $table = "orders_express";
        $expressFieldsColumn = 'c.front_address,b.distance,c.storename as shop_name,b.receiver,b.receiver_tel,b.receiver_address,a.id,a.shop_express_no,a.orders_id,a.shop_no,a.order_no,a.ph_no,a.express_type,a.shop_delivery_time,a.shop_pickup_time,a.express_order_no,a.express_fee,a.express_courier,a.express_mobile,a.express_longtitude,a.express_latitude,a.status,a.error_remark';
        $Sql = "SELECT $expressFieldsColumn from $table a 
left join orders b ON a.orders_id = b.id  and a.status = b.status 
left join xd_store c on c.store_id = a.shop_no
where $where order by a.createdt desc $limit";

//        echo $Sql;
        $res = $this->model->getAny($Sql);
        $rsp_list = [];
        if (!empty($res)) {
            while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
                $rsp_list[] = $row;
            }
        }


        if($rsp_list && count((array) $rsp_list ) > 0){
            foreach($rsp_list as &$r1){
                $where_field_edit = array("AND" => array("=" => array( 'isdeleted' => 0, 'status' => 1, 'orders_id' => $r1['orders_id'])));
                $shop_delivery_address = $this->model->getItemByOther($where_field_edit,'shop_delivery_address');
                if($shop_delivery_address && is_array($shop_delivery_address) && count($shop_delivery_address) > 0 ){
                    $r1['receiver'] = $shop_delivery_address[0]['receiver_name'];
                    $r1['receiver_tel'] = $shop_delivery_address[0]['receiver_tel'];
                    $r1['receiver_address'] = $shop_delivery_address[0]['receiver_address'];
                    $r1['distance'] = $shop_delivery_address[0]['distance'];
                }

                $where = array('AND'=>array('='=>array('order_no' => $r1['shop_express_no'],'shop_no' => $r1['shop_no'],'status' => 1,'isdeleted' => 0)));
                $data = $this->model->getItemByOther($where, 'tip_list');

                if($data){
                    foreach($data as $k=>$t){
                        $r1['tip'] += $t['price'];
                    }
                }
            }
        }
        return $rsp_list;
    }


    /**
     * 订单列表
     */
    public function OrdersListAction() {
        $getPos_no = file_get_contents("php://input");
        $file = 'orders_list';
        self::WriteReception($file,$getPos_no);
        $Data = json_decode($getPos_no, true);
        if($_SERVER['REQUEST_METHOD'] !== 'POST'){
            self::WriteResponse($file,0,'Request type error','');
        }

        if($_SERVER['CONTENT_TYPE'] !== 'application/json'){
            self::WriteResponse($file,0,'Request data format error','');
        }

        if(!$Data || !is_array($Data)){
            self::WriteResponse($file,0,'数据结构异常','');
        }

        $validate = ['check_code'=>'check','mobile'=>'phone','type'=>'NotNull'];
        self::Verify($Data,$validate,$file,Data::$VERSION);
        $rsp_list = $this->orderInfo($Data['type'],$Data['mobile'],$Data['page'],3);
        self::WriteResponse($file,1,'',$rsp_list);
    }


    /**
     * 骑手验证
     */
    public function CheckRiderAction(){
        $getPos_no = file_get_contents("php://input");
        $file = 'store_list';
        self::WriteReception($file,$getPos_no);
        $Data = json_decode($getPos_no, true);
        if($_SERVER['REQUEST_METHOD'] !== 'POST'){
            self::WriteResponse($file,0,'Request type error','');
        }

        if($_SERVER['CONTENT_TYPE'] !== 'application/json'){
            self::WriteResponse($file,0,'Request data format error','');
        }

        if(!$Data || !is_array($Data)){
            self::WriteResponse($file,0,'数据结构异常','');
        }

        $validate = ['check_code'=>'check','mobile'=>'phone'];
        self::Verify($Data,$validate,$file,Data::$VERSION);

        $r = $this->model->CheckRider($Data);
        if($r['result']['status'] == 1){
            self::WriteResponse($file,$r['result']['status'],$r['result']['msg'],$r['result']['data']);
        }
        self::WriteResponse($file,0,'','');

    }

    /**
     * 筛选区域下门店信息
     */
    public function getAreaShopAction(){
        $getPos_no = file_get_contents("php://input");
        $file = 'store_list';
        self::WriteReception($file,$getPos_no);
        $Data = json_decode($getPos_no, true);
        if($_SERVER['REQUEST_METHOD'] !== 'POST'){
            self::WriteResponse($file,0,'Request type error','');
        }

        if($_SERVER['CONTENT_TYPE'] !== 'application/json'){
            self::WriteResponse($file,0,'Request data format error','');
        }

        if(!$Data || !is_array($Data)){
            self::WriteResponse($file,0,'数据结构异常','');
        }

        $validate = ['check_code'=>'check','area'=>'string'];
        self::Verify($Data,$validate,$file,Data::$VERSION);

        $r = $this->model->GetStores($Data);
        if($r['result']['status'] == 1){
            self::WriteResponse($file,$r['result']['status'],$r['result']['msg'],$r['result']['list']);
        }
        self::WriteResponse($file,0,'','');

    }


    /**
     * 抢单
     */
    public function GrabAction(){

        $getPos_no = file_get_contents("php://input");
        $file = 'Gra';
        self::WriteReception($file,$getPos_no);
        $Data = json_decode($getPos_no, true);
        if($_SERVER['REQUEST_METHOD'] !== 'POST'){
            self::WriteResponse($file,0,'Request type error','');
        }

        if($_SERVER['CONTENT_TYPE'] !== 'application/json'){
            self::WriteResponse($file,0,'Request data format error','');
        }

        if(!$Data || !is_array($Data)){
            self::WriteResponse($file,0,'数据结构异常','');
        }

        $validate = ['check_code'=>'check','express_id'=>'string','mobile'=>'phone'];
        self::Verify($Data,$validate,$file,Data::$VERSION);

        $result = $this->model->couponshareexecute($Data['express_id'],$Data['mobile']);

        if($result == 200)
            self::WriteResponse($file,1,'抢单成功','');
        else
            self::WriteResponse($file,0,'该订单已被抢','');
    }


    /**
     * 订单详情
     */
    public function finishOrderDetailsAction(){
        $getPos_no = file_get_contents("php://input");
        $file = 'finishOrderDetails';
        self::WriteReception($file,$getPos_no);
        $Data = json_decode($getPos_no, true);
        if($_SERVER['REQUEST_METHOD'] !== 'POST'){
            self::WriteResponse($file,0,'Request type error','');
        }

        if($_SERVER['CONTENT_TYPE'] !== 'application/json'){
            self::WriteResponse($file,0,'Request data format error','');
        }

        if(!$Data || !is_array($Data)){
            self::WriteResponse($file,0,'数据结构异常','');
        }

        $validate = ['check_code'=>'check','express_id'=>'string','mobile'=>'phone'];
        self::Verify($Data,$validate,$file,Data::$VERSION);

        $table = 'orders_express';
        $express_id = (!empty($Data['express_id'])) ? (int)$Data['express_id'] : '';
        $type = (!empty($Data['type'])) ? (int) $Data['type'] : '';
        $where = ['AND'=>['='=>['id'=>$express_id, "isdeleted"=>0]]];
        $orderExpressInfo = $this->model->getItemByOther($where,$table);

        # 订单
        $whereOrder = ['AND'=>['='=>['ph_no'=>$orderExpressInfo[0]['ph_no'], "isdeleted"=>0]]];
        $orderInfo = $this->model->getItemByOther($whereOrder,'orders');

        # 商品详情
        $whereOrderProduct = ['AND'=>['='=>['ph_no'=>$orderExpressInfo[0]['ph_no']]]];
        $orderProductInfo = $this->model->getItemByOther($whereOrderProduct,'orders_product');

        # 门店详情
        $whereShop = ['AND'=>['='=>['store_id'=>$orderExpressInfo[0]['shop_no']]]];
        $shopInfo = $this->model->getItemByOther($whereShop,'xd_store');

        $where_field_edit = array("AND" => array("=" => array( 'isdeleted' => 0, 'status' => 1, 'orders_id' => $orderExpressInfo[0]['orders_id'])));
        $shop_delivery_address = $this->model->getItemByOther($where_field_edit,'shop_delivery_address');

        if($shop_delivery_address && is_array($shop_delivery_address) && count($shop_delivery_address) > 0 ){
            $orderInfo[0]['receiver'] = $shop_delivery_address[0]['receiver_name'];
            $orderInfo[0]['receiver_tel'] = $shop_delivery_address[0]['receiver_tel'];
            $orderInfo[0]['receiver_address'] = $shop_delivery_address[0]['receiver_address'];
            $orderInfo[0]['distance'] = $shop_delivery_address[0]['distance'];

        }
        $orderExpressInfo['orderInfo'] = $orderInfo[0];
        $orderExpressInfo['orderProductInfo'] = $orderProductInfo;
        $orderExpressInfo['shopInfo'] = $shopInfo[0];
        $orderExpressInfo['count'] = count((array)$orderProductInfo);
        foreach($orderExpressInfo as &$r){
            $where = array('AND'=>array('='=>array('order_no' => $r['shop_express_no'],'shop_no' => $r['shop_no'],'status' => 1,'isdeleted' => 0)));
            $data = $this->model->getItemByOther($where, 'tip_list');
            if($data){
                $r['tip_arr'] = $data;
            }
        }
        self::WriteResponse($file,1,'',$orderExpressInfo);
    }


    /**
     * 确认取货
     */
    public function assPickAction(){
        $express_id = (!empty($this->params['express_id'])) ? (int) $this->params['express_id'] : '';

        $getPos_no = file_get_contents("php://input");
        $file = 'assPick';
        self::WriteReception($file,$getPos_no);
        $Data = json_decode($getPos_no, true);
        if($_SERVER['REQUEST_METHOD'] !== 'POST'){
            self::WriteResponse($file,0,'Request type error','');
        }

        if($_SERVER['CONTENT_TYPE'] !== 'application/json'){
            self::WriteResponse($file,0,'Request data format error','');
        }

        if(!$Data || !is_array($Data)){
            self::WriteResponse($file,0,'数据结构异常','');
        }

        $validate = ['check_code'=>'check','express_id'=>'string','mobile'=>'phone'];
        self::Verify($Data,$validate,$file,Data::$VERSION);

        $express_id = $Data['express_id'];
        $whereExp = ['AND'=>['='=>['id'=>$express_id]]];
        $ExpInfo = $this->model->getItemByOther($whereExp,'orders_express');

        if(!$ExpInfo){
            self::WriteResponse($file,0,'读取数据失败','');
        }
        $field['updatedt'] = 'now()';
        $field['status'] = 4;
        $where_fields = array("AND" => array("=" => array('id' => $express_id, "isdeleted" => 0)));
        $e = $this->model->updateItem($field, $where_fields, 'orders_express');


        $field = array();
        $field['updatedt'] = 'now()';
        $field['status'] = 4;
        $where_fields = array("AND" => array("=" => array('ph_no' => $ExpInfo[0]['ph_no'], "isdeleted" => 0)));
        $r = $this->model->updateItem($field, $where_fields, 'orders');

        $where = array("AND" => array("=" => array('ph_no' => $ExpInfo[0]['ph_no'])));
        $UserInfo = $this->model->getItemByOther( $where, 'orders');
        # 数据库更新成功
        if($r && $e){
            # 新增配送信息
            $whereExpressData = array("AND" => array("=" => array('shop_express_no'=>$ExpInfo[0]['shop_express_no'], "isdeleted"=>0)));
            $expDataInfo = $this->model->getItemByOther($whereExpressData,'express_data');
            if($expDataInfo){
                # 新增配送信息
                $status = 4;
                $express_order['shop_express_no'] = $ExpInfo[0]['shop_express_no'];
                $express_order['express_order_no'] = $ExpInfo[0]['order_no'];
                $express_order['express_type'] = $ExpInfo[0]['express_type'];
                $expd = $this->model->addExpressData($express_order,$status);
                if($expd){
                    $fieldExpData = array();
                    $fieldExpData['express_code'] = 200;
                    $fieldExpData['express_code_desc'] = '自建骑手取单成功';
                    $fieldExpData['express_data'] = '';
                    $fieldExpData['result_code'] = 0;
                    $this->model->updateExpressData($expd,$fieldExpData);
                }
            }
            self::WriteResponse($file,1,'取货成功','');
        }else{
            self::WriteResponse($file,0,'更新失败','');
        }
    }




    /**
     * 订单送达
     */
    public function finishAction(){
        $getPos_no = file_get_contents("php://input");
        $file = 'finish';
        self::WriteReception($file,$getPos_no);
        $Data = json_decode($getPos_no, true);
        if($_SERVER['REQUEST_METHOD'] !== 'POST'){
            self::WriteResponse($file,0,'Request type error','');
        }

        if($_SERVER['CONTENT_TYPE'] !== 'application/json'){
            self::WriteResponse($file,0,'Request data format error','');
        }

        if(!$Data || !is_array($Data)){
            self::WriteResponse($file,0,'数据结构异常','');
        }
        $validate = ['check_code'=>'check','mobile'=>'phone'];
        self::Verify($Data,$validate,$file,Data::$VERSION);
        $express_id = $Data['express_id'];
        $remark = $Data['txt_info'];
        $finishselect = $Data['radio_info'];

        if(!$express_id || !$finishselect ){
            echo json_encode(['status'=>0,'msg'=>'参数错误','code'=>3003]);exit;
        }
        $whereExp = ['AND'=>['='=>['id'=>$express_id]]];
        $ExpInfo = $this->model->getItemByOther($whereExp,'orders_express');
        if(!$ExpInfo){
            self::WriteResponse($file,0,'读取数据失败','');exit;
        }
        if($finishselect == 6){
            $status = $finishselect;
            $express_code = 6001;
            $express_code_desc = '订单配送异常';
        }else{
            $status = 5;
            $express_code = 200;
            $express_code_desc = '自建骑手配送完成';
        }
        $field['updatedt'] = 'now()';
        $field['status'] = $status;
        $field['finish_select'] = $finishselect;
        $field['error_remark'] = $remark;
        $where_fields = array("AND" => array("=" => array('id' => $express_id, "isdeleted" => 0)));
        $e = $this->model->updateItem($field, $where_fields, 'orders_express');


        $field = array();
        $field['updatedt'] = 'now()';
        if($finishselect == 6){
            $field['status'] = $finishselect;
        }else{
            $field['status'] = 5;
        }
        $where_fields = array("AND" => array("=" => array('ph_no' => $ExpInfo[0]['ph_no'], "isdeleted" => 0)));
        $r = $this->model->updateItem($field, $where_fields, 'orders');


        if($r && $e){
            # 新增配送信息
            $whereExpressData = array("AND" => array("=" => array('shop_express_no'=>$ExpInfo[0]['shop_express_no'], "isdeleted"=>0)));
            $expDataInfo = $this->model->getItemByOther($whereExpressData,'express_data');
            if($expDataInfo){
                # 新增配送信息
                $express_order['shop_express_no'] = $ExpInfo[0]['shop_express_no'];
                $express_order['express_order_no'] = $ExpInfo[0]['order_no'];
                $express_order['express_type'] = $ExpInfo[0]['express_type'];
                $expd = $this->model->addExpressData($express_order,$status);
                if($expd){
                    $fieldExpData = array();
                    $fieldExpData['express_code'] = $express_code;
                    $fieldExpData['express_code_desc'] = $express_code_desc;
                    $fieldExpData['express_data'] = '';
                    $fieldExpData['result_code'] = 0;
                    $this->model->updateExpressData($expd,$fieldExpData);
                }

            }
            self::WriteResponse($file,1,'确认取货成功','');
        }else{
            self::WriteResponse($file,0,'系统订单状态更新失败','');
        }

    }



    /**
     * 个人信息
     */
    public function personageInfoAction(){
        $getPos_no = file_get_contents("php://input");
        $file = 'personageInfo';
        self::WriteReception($file,$getPos_no);
        $Data = json_decode($getPos_no, true);
        if($_SERVER['REQUEST_METHOD'] !== 'POST'){
            self::WriteResponse($file,0,'Request type error','');
        }

        if($_SERVER['CONTENT_TYPE'] !== 'application/json'){
            self::WriteResponse($file,0,'Request data format error','');
        }

        if(!$Data || !is_array($Data)){
            self::WriteResponse($file,0,'数据结构异常','');
        }
        $validate = ['check_code'=>'check','mobile'=>'phone'];
        self::Verify($Data,$validate,$file,Data::$VERSION);

        $table = 'riders';
        $tel = $Data['mobile'];
        $where_fields = array("AND" => array("=" => array("tel" => $tel)));
        $ridersResult = $this->model->getItemByOther($where_fields, $table);

        $orderby = array('id' => 'asc');
        $like_fields = [];
        $where['AND']['=']['parent_code'] = 1;
        $where_city['AND']['=']['is_parent'] = 1;
        $where_city['AND']['>']['parent_code'] = 1;
        $where_area['AND']['=']['is_parent'] = 0;
        $where_area['AND']['>']['parent_code'] = 1;
        $province = $this->model->getAll($where,'area',$orderby,$like_fields);
        $city = $this->model->getAll($where_city,'area',$orderby,$like_fields);
        $area = $this->model->getAll($where_area,'area',$orderby,$like_fields);

        $storeSql = "SELECT store_id,storename from xd_store where (status = 2 or status = 4 or status = 5)  and isdeleted = 0";
        $store = $this->model->getAny($storeSql);
        if (!empty($store)) {
            while ($Stores = mysqli_fetch_array($store, MYSQLI_ASSOC)) {
                $row[] = $Stores;
            }
        }
        foreach ($ridersResult as &$v1){
            foreach ($province as $p){
                if($v1['province'] == $p['code']){
                    $v1['province_name'] = $p['fullname'];
                }
                if($v1['service_province'] == $p['code']){
                    $v1['service_province_name'] = $p['fullname'];
                }
            }
        }

        foreach ($ridersResult as &$v2){
            foreach ($city as $c){
                if($v2['city'] == $c['code']){
                    $v2['city_name'] = $c['fullname'];
                }
                if($v2['service_city'] == $c['code']){
                    $v2['service_city_name'] = $c['fullname'];
                }
            }
        }

        foreach ($ridersResult as &$v3){
            foreach ($area as $a){
                if($v3['area'] == $a['code']){
                    $v3['area_name'] = $a['fullname'];
                }
                if($v3['service_area'] == $a['code']){
                    $v3['service_area_name'] = $a['fullname'];
                }
            }
        }

        foreach ($ridersResult as &$v4){
            if($row){
                foreach ($row as $r){
                    if($v4['service_shop_no'] == $r['store_id']){
                        $v4['shopname'] = $r['storename'];
                    }
                }
            }

        }

        self::WriteResponse($file,1,'',$ridersResult[0]);
    }



    /**
     * 常见问题
     */
    public function FQAAction()
    {
        $getPos_no = file_get_contents("php://input");
        $file = 'fqa';
        self::WriteReception($file,$getPos_no);
        $Data = json_decode($getPos_no, true);
        if($_SERVER['REQUEST_METHOD'] !== 'POST'){
            self::WriteResponse($file,0,'Request type error','');
        }

        if($_SERVER['CONTENT_TYPE'] !== 'application/json'){
            self::WriteResponse($file,0,'Request data format error','');
        }

        if(!$Data || !is_array($Data)){
            self::WriteResponse($file,0,'数据结构异常','');
        }
        $validate = ['check_code'=>'check'];
        self::Verify($Data,$validate,$file,Data::$VERSION);


        $table = "fqa";
        $orderby = array('id' => 'asc');
        $where_fields['AND']['=']['status'] = 1;
        $where_fields['AND']['=']['isdeleted'] = 0;
        $expressFieldsColumn = '';
        $rsp_list = $this->model->getAll($where_fields, $table, $orderby, $expressFieldsColumn );

        self::WriteResponse($file,1,'',$rsp_list);
    }

    /**
     * 常见问题详情
     */
    public function FQADetailsAction(){
        $table = "fqa";
        $getPos_no = file_get_contents("php://input");
        $file = 'fqaDetail';
        self::WriteReception($file,$getPos_no);
        $Data = json_decode($getPos_no, true);
        if($_SERVER['REQUEST_METHOD'] !== 'POST'){
            self::WriteResponse($file,0,'Request type error','');
        }

        if($_SERVER['CONTENT_TYPE'] !== 'application/json'){
            self::WriteResponse($file,0,'Request data format error','');
        }

        if(!$Data || !is_array($Data)){
            self::WriteResponse($file,0,'数据结构异常','');
        }
        $validate = ['check_code'=>'check'];
        self::Verify($Data,$validate,$file,Data::$VERSION);


        $row = $this->model->getItemById($Data["fid"], $table);

        self::WriteResponse($file,1,'',$row);
    }




    /**
     * 消息中心
     */
    public function MessageContenAction(){
        $getPos_no = file_get_contents("php://input");
        $file = 'MessageConten';
        self::WriteReception($file,$getPos_no);
        $Data = json_decode($getPos_no, true);
        if($_SERVER['REQUEST_METHOD'] !== 'POST'){
            self::WriteResponse($file,0,'Request type error','');
        }

        if($_SERVER['CONTENT_TYPE'] !== 'application/json'){
            self::WriteResponse($file,0,'Request data format error','');
        }

        if(!$Data || !is_array($Data)){
            self::WriteResponse($file,0,'数据结构异常','');
        }
        $validate = ['check_code'=>'check'];
        self::Verify($Data,$validate,$file,Data::$VERSION);


        $mobile = $Data['mobile'];
        $where = '';
        if($mobile){
            $where.=" AND riders_tel = $mobile ";
        }
        $sql = "SELECT * FROM news  WHERE (status = 9 OR status = 7 OR status = 3) $where AND isdeleted = 0  order by ico asc";
        $res = $this->model->getAny($sql);
        if (!empty($res)) {
            while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
                $rsp_list[] = $row;
            }
        }
        $count = count($rsp_list);
        $rsp_list['count'] = $count;
        self::WriteResponse($file,1,'',$rsp_list);
    }


    /**
     * 消息详情
     */
    public function MessageDetailsAction(){
        $getPos_no = file_get_contents("php://input");
        $file = 'MessageDetails';
        self::WriteReception($file,$getPos_no);
        $Data = json_decode($getPos_no, true);
        if($_SERVER['REQUEST_METHOD'] !== 'POST'){
            self::WriteResponse($file,0,'Request type error','');
        }

        if($_SERVER['CONTENT_TYPE'] !== 'application/json'){
            self::WriteResponse($file,0,'Request data format error','');
        }

        if(!$Data || !is_array($Data)){
            self::WriteResponse($file,0,'数据结构异常','');
        }

        $validate = ['check_code'=>'check'];
        self::Verify($Data,$validate,$file,Data::$VERSION);
        $table = "news";
        $row = $this->model->getItemById($Data['nid'], $table);

        $data['ico'] = 2;
        $data['updatedt'] = 'now()';
        $where_fields = array("AND" => array("=" => array('id' => $Data['nid'])));
        $this->model->updateItem($data, $where_fields, $table);

        self::WriteResponse($file,1,'',$row);
    }


    /**
     * 骑手经纬度
     */
    public function getLocationAction(){

        $getPos_no = file_get_contents("php://input");
        $file = 'Gra';
        self::WriteReception($file,$getPos_no);
        $Data = json_decode($getPos_no, true);
        if($_SERVER['REQUEST_METHOD'] !== 'POST'){
            self::WriteResponse($file,0,'Request type error','');
        }

        if($_SERVER['CONTENT_TYPE'] !== 'application/json'){
            self::WriteResponse($file,0,'Request data format error','');
        }

        if(!$Data || !is_array($Data)){
            self::WriteResponse($file,0,'数据结构异常','');
        }
        $validate = ['check_code'=>'check','mobile'=>'phone'];
        self::Verify($Data,$validate,$file,Data::$VERSION);

        $rsp_list_3 = $this->orderInfo(3,$Data['mobile'],1,1);
        $rsp_list_4 = $this->orderInfo(4,$Data['mobile'],1,1);
        if(count((array) $rsp_list_3) > 0  || count((array) $rsp_list_4) > 0){
            $where_fields = array("AND" => array("=" => array('mobile' => $Data['mobile'])));
            $riders_location = $this->model->getItemByOther($where_fields,'riders_location');

            $field = array();
            $field['mobile'] = $Data['mobile'];
            $field['lng'] = $Data['lng'];
            $field['lat'] = $Data['lat'];
            if($riders_location && count((array) $riders_location) > 0){
                $field['updatedt'] = 'now()';
                $this->model->updateItem($field, $where_fields, 'riders_location');
            }else{
                $field['createdt'] = 'now()';
                $this->model->addItem($field, 'riders_location');
            }
        }else{
            self::WriteResponse($file,0,'normal stop','');
        }
    }



    /**
     * 筛选时间段内 个人收入
     */
    public function getMyWalletAction(){
        $getPos_no = file_get_contents("php://input");
        $file = 'myWallet';
        self::WriteReception($file,$getPos_no);
        $Data = json_decode($getPos_no, true);
        if($_SERVER['REQUEST_METHOD'] !== 'POST'){
            self::WriteResponse($file,0,'Request type error','');
        }

        if($_SERVER['CONTENT_TYPE'] !== 'application/json'){
            self::WriteResponse($file,0,'Request data format error','');
        }

        if(!$Data || !is_array($Data)){
            self::WriteResponse($file,0,'数据结构异常','');
        }
        $validate = ['check_code'=>'check','startdt'=>'string','enddt'=>'string','mobile'=>'phone'];
        self::Verify($Data,$validate,$file,Data::$VERSION);


        $startdt =$Data['startdt'];
        $enddt =$Data['enddt'];
        $mobile =$Data['mobile'];
        $where_fields = "express_type = 'self' AND isdeleted = 0 AND (status = 5 OR status = 6 OR status = 7) AND express_mobile = '$mobile'";
        if($startdt){
            $where_fields .= " AND updatedt >= '$startdt 00:00:00'";
        }
        if($enddt){
            $where_fields .= " AND updatedt <= '$enddt 23:59:59'";
        }
        $sql = "SELECT id,ph_no,updatedt,express_fee FROM orders_express  WHERE $where_fields  order by id asc";
        $res = $this->model->getAny($sql);
        $rsp_list = [];
        if (!empty($res)) {
            while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
                $rsp_list[] = $row;
            }
        }
        $money = 0;
        if($rsp_list && count((array) $rsp_list) > 0){
            foreach($rsp_list as $v){
                $money += $v['express_fee'];
            }
        }

        $rsp_list_n['list'] = $rsp_list;
        if($money > 0) $rsp_list_n['money'] = $money;
        self::WriteResponse($file,1,'',$rsp_list_n);
    }

}
